package com.flight.controller;

import com.flight.model.entity.Passenger;
import com.flight.model.service.PassengerService;
import com.flight.model.service.impl.PassengerServiceImpl;
import com.flight.view.LoginFrame;
import com.flight.view.MainFrame;
import com.flight.view.components.MessageDialog;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginController {
    private LoginFrame loginFrame;
    private PassengerService passengerService;

    public LoginController() {
        loginFrame = new LoginFrame();
        passengerService = new PassengerServiceImpl(); // 初始化服务
        bindEvent();
        loginFrame.setVisible(true); // 显示登录窗口
    }

    private void bindEvent() {
        loginFrame.addLoginListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取登录表单数据（确保LoginFrame中定义了这些方法）
                String passengerId = loginFrame.getPassengerId(); // 身份证号
                String password = loginFrame.getPassword(); // 密码

                // 校验输入
                if (passengerId.isEmpty() || password.isEmpty()) {
                    MessageDialog.showError(loginFrame, "身份证号和密码不能为空！");
                    return;
                }

                // 调用服务校验用户
                Passenger passenger = passengerService.getPassengerById(passengerId);
                if (passenger == null || !passenger.getPassword().equals(password)) {
                    MessageDialog.showError(loginFrame, "身份证号或密码错误！");
                    return;
                }

                // 登录成功，跳转主界面
                loginFrame.dispose(); // 关闭登录窗口
                MainFrame mainFrame = new MainFrame(passengerId);
                new BookingController(mainFrame, passengerId); // 初始化主控制器
                mainFrame.setVisible(true);
            }
        });
    }

    // 提供显示登录窗口的方法（供外部调用）
    public void showLoginFrame() {
        loginFrame.setVisible(true);
    }
}